﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace _07_WebHost.Host
{
    public class WebApplicationBuilder
    {
        public IServiceCollection Services { get; private set; }

        public ConfigurationManager Configuration { get; private set; }

        public ILoggingBuilder Logging { get; private set; }

        public WebApplicationBuilder()
        {
            Services = new ServiceCollection();
            Configuration = new ConfigurationManager();
            Logging = new LoggingBuilder(Services);
        }


        public WebApplication Build()
        {
            BuildConfiguration();
            BuildLogging();
            return new WebApplication(BuildServiceProvider());
        }

        private IServiceProvider BuildServiceProvider()
        {
            return Services.BuildServiceProvider();
        }

        private void BuildLogging()
        {
            Logging.AddConsole();
            Logging.AddConfiguration(Configuration.GetSection("Logging"));
        }

        private void BuildConfiguration()
        {
            Configuration.SetBasePath(Directory.GetCurrentDirectory());
            Configuration.AddJsonFile("appsettings.json", false, true);
        }

        private sealed class LoggingBuilder : ILoggingBuilder
        {
            public LoggingBuilder(IServiceCollection services)
            {
                Services = services;
            }

            public IServiceCollection Services { get; }
        }
    }
}
